﻿using Microsoft.AspNetCore.Mvc;

using PLCS.Application.Contracts.TrayApp.Dtos;
using PLCS.Domain.Equipments;
using PLCS.Domain.Shared.Enums;
using PLCS.Domain.Shared.Tasks;
using PLCS.Domain.Stations;
using PLCS.Domain.Tasks;
using PLCS.Domain.Trays;
using PLCS.EquipmentService.ParsersHelpers;
using PLCS.SocialHttpApi.Attributes;
using PLCS.SocialHttpApi.Models;

using System.ComponentModel;
using System.Security.Policy;

using Volo.Abp.AspNetCore.Mvc;

namespace PLCS.SocialHttpApi.Controllers;

[Route("api/[controller]/[action]")]
[ApiController]
[ServiceFilter(typeof(LogActionFilter))]
public class WMSController : AbpControllerBase
{
    private readonly TaskManager _taskManager;
    private readonly IStationRepository _stationRepository;
    private readonly ITrayRepository _trayRepository;
    private readonly TaskParser _taskParser;
    private readonly ITaskRepository _taskRepository;
    private readonly IEquipmentRepository _equipmentRepository;
    private readonly IInstructionRepository _instructionRepository;

    public WMSController(ITrayRepository trayRepository, IStationRepository stationRepository, TaskManager taskManager, TaskParser taskParser, ITaskRepository taskRepository, IEquipmentRepository equipmentRepository, IInstructionRepository instructionRepository)
    {
        _trayRepository = trayRepository;
        _stationRepository = stationRepository;
        _taskManager = taskManager;
        _taskParser = taskParser;
        _taskRepository = taskRepository;
        _equipmentRepository = equipmentRepository;
        _instructionRepository = instructionRepository;
    }

    [HttpPost]
    [Description("WMS从WCS读取设备状态")]
    [Requester("WMS")]
    public async Task<Response_WMS> Wms_to_wcs_readstatus(Request_WMS_ReadStatus request)
    {
        string seqNo = request.header.seqNo;
        var model = request.body;
        string eqNo = model.eqNo;
        var equipment = await _equipmentRepository.GetByEquipmentNoAsync(eqNo);
        if (equipment == null)
        {
            return new Response_WMS(new ResponseHeader("E", seqNo, $"设备号‘{eqNo}‘不存在"));
        }
        var station = await _stationRepository.GetStationByNumAsync(equipment.ContainStationNos);
        if (station == null)
        {
            return new Response_WMS(new ResponseHeader("E", seqNo, $"设备号‘{eqNo}‘不存在"));
        }
        int status = equipment.IsLocked == YesNo.是 ? 1 : equipment.IsUse == YesNo.否 ? 1 : 0;
        return new Response_WMS(new ResponseHeader("S", seqNo, ""), new { Status = status, HaveStatus = (int)station.HaveStatus });
    }

    [HttpPost]
    [Description("WMS给WCS下发任务")]
    [Requester("WMS")]
    public async Task<Response_WMS> Wms_to_plcs_task_release(Request_WMS_task_release request)
    {
        string seqNo = request.header.seqNo;
        var model = request.body;
        var endPosTasks = await _taskRepository.GetUnfinshedAboutRunningTaskAsync();
        if (endPosTasks.Any(x => x.TrayNo == model.TrayCode) || endPosTasks.Any(x=>x.TaskId_Higher==model.WmsTaskId))
            return new Response_WMS(new ResponseHeader("E", seqNo, $"托盘{model.TrayCode}任务已存在"));

        switch (model.TaskType)
        {
            case 1:
                var task = new TaskModel(0, model.Level, model.From, model.To, null, TaskType.出库, "WMS下发", model.TrayCode);
                task.SetUpperTaskId(model.WmsTaskId);
                await _taskManager.InsertAsync(task);
                break;

            case 2:
                var task2 = new TaskModel(0, model.Level, model.From, model.To, null, TaskType.入库, "WMS下发", model.TrayCode);
                task2.SetUpperTaskId(model.WmsTaskId);
                await _taskManager.InsertAsync(task2);
                break;

            default:
                break;
        }
        return new Response_WMS(new ResponseHeader("S", seqNo, ""));
    }

    [HttpPost]
    [Description("WMS给WCS异常处理")]
    [Requester("WMS")]
    public async Task<Response_WMS> Wms_to_wcs_unusualhand(Request_WMS_Unusualhand request)
    {
        string seqNo = request.header.seqNo;
        var model = request.body;
        var tasks = await _taskRepository.GetUnfinshedAboutRunningTaskAsync();
        var task = tasks.Where(x => x.TaskId_Higher == model.wmsTaskId).FirstOrDefault();
        if (task == null)
            return new Response_WMS(new ResponseHeader("E", seqNo, $"任务‘{model.wmsTaskId}‘不存在或已完成"));
        switch (model.taskType)
        {
            case "1":
                if (task.TaskStatus == Domain.Shared.Tasks.TaskStatus.执行中)
                    return new Response_WMS(new ResponseHeader("E", seqNo, $"任务‘{model.wmsTaskId}‘正在执行中，无法取消"));

                await _taskRepository.HardDeleteAsync(task.Id);
                break;

            case "2":
                var instructions = await _instructionRepository.GetListAsync(x => x.TaskId == task.Id);
                if (instructions != null)
                {
                    foreach (var item in instructions.OrderBy(x => x.InstructionNo))
                    {
                        item.ChangeStatus(Domain.Shared.Tasks.InstructionStatus.已完成);
                    }
                    await _instructionRepository.UpdateManyAsync(instructions);
                }
                break;

            default:
                break;
        }
        return new Response_WMS(new ResponseHeader("S", seqNo, ""));
    }
}